<template>
    <div class="item-one" ref="itemOne">
        <div class="title">
            <span>核销记录</span>
            <div>
                <el-button type="primary" :disabled="exxxx" @click="joinexportlist()">导出任务列表</el-button>
                <el-button type="primary" :disabled="exxxx" @click="merchantexcel()"><i class="el-icon-download"></i>申请导出
                </el-button>
                <el-button @click="chengecz" icon="el-icon-refresh"></el-button>
            </div>
        </div>
        <div class="container">
            <div class="screeningBox">
              
                <el-input v-model="input1" class="chengeinout" clearable placeholder="请输入优惠券码"></el-input>

                <el-autocomplete
                        v-model="merchantName"
                        v-if="this.userInfo.rolesId != 5 && this.userInfo.rolesId != 6"
                        class="chengeinout"
                        :fetch-suggestions="merchantslist"
                        :trigger-on-focus="false"
                        :debounce="300"
                        placeholder="请选择商户"
                        @select="merid"
                ></el-autocomplete>

                <el-autocomplete
                        v-model="shopName"
                        v-if="this.userInfo.rolesId != 6"
                        class="chengeinout"
                        :fetch-suggestions="allshops"
                        :trigger-on-focus="false"
                        :debounce="300"
                        placeholder="请选择指定门店"
                        @select="shopid"
                ></el-autocomplete>

                <el-input v-model="outWfNo" class="chengeinout" clearable placeholder="请输入核销记录号"></el-input>
                <el-input v-model="channelOrderNo" class="chengeinout" clearable placeholder="请输入通道订单号"></el-input>
                <el-input v-model="channelTransId" class="chengeinout" clearable placeholder="请输入通道核销流水号"></el-input>
                <el-select v-model="status" class="chengeinout" clearable placeholder="请选择状态">
                    <el-option
                            v-for="item in options2"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
                <el-select v-model="channelType" class="chengeinout" clearable placeholder="通道类型">
                    <el-option keys="1" label="全部" value=""></el-option>
                    <el-option v-for="(item,index) in channelslist" :key="index" :label="item.options" :value="item.code"></el-option>
                </el-select>

                <el-input v-model="input6" class="chengeinout" clearable placeholder="请输入操作员"></el-input>
              

                <el-date-picker
                        class="date-picker"
                        v-model="input7"
                        type="datetimerange"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        :picker-options="pickerOptions1"
                        :clearable='false'
                        :default-time="['00:00:00', '23:59:59']"
                        end-placeholder="结束日期">
                </el-date-picker>

                <el-button class="chengebutton" @click="chengess" type="primary">搜索</el-button>
                <el-button class="chengebutton" @click="chengecz" type="primary">重置</el-button>


            </div>
        </div>
        <div class="statistical">
            <div class="statisticalitem">
                <div>总核销笔数</div>
                <div>
                    <span>{{count}}</span> 笔
                </div>
            </div>
            <div class="statisticalitem">
                <div>订单总金额</div>
                <div>
                    <span>{{amount /100}}</span> 元
                </div>
            </div>
            <div class="statisticalitem">
                <div>总优惠金额</div>
                <div>
                    <span>{{couponAmount /100}}</span> 元
                </div>
            </div>

        </div>
        <div class="tableBox">
            <el-table
                    ref="multipleTable"
                    :show-overflow-tooltip="true"
                    :data="merchantarr"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                    stripe
                    :header-cell-style="tableHeaderColor"
                    v-loading="loading"
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" align="center"></el-table-column>
               
                <el-table-column width="240" label="核销时间?核销记录号" align="center" :render-header="renderheader">
                    <template slot-scope="scope">
                        <div>{{scope.row.createTime}}</div>
                        <div>{{scope.row.outWfNo}}</div>
                    </template>
                </el-table-column>
                <el-table-column property="couponCode" width="120" label="券码" align="center"></el-table-column>
                <el-table-column property="merchantName"  width="100" label="商户名称" align="center"></el-table-column>
                <el-table-column property="shopName"  width="100" label="门店名称" align="center"></el-table-column>
                <el-table-column property="writeOffAmount" label="支付订单金额(元)" align="center">
                    <template slot-scope="scope">
                        <div>{{scope.row.writeOffAmount/100}}</div>
                    </template>
                </el-table-column>
                <el-table-column width="100" label="通道名称?券面额(元)" align="center" :render-header="renderheader">
                    <template slot-scope="scope">
                        <div>{{scope.row.channelTypeName}}</div>
                        <div>{{scope.row.couponAmount/100}}</div>
                    </template>
                </el-table-column>

                <el-table-column property="channelOrderNo" width="150" label="通道订单号" align="center"></el-table-column>
                <el-table-column property="channelTransId" width="120" label="通道核销流水号" align="center"></el-table-column>
                <el-table-column width="80" label="状态" align="center">
                    <template slot-scope="scope">
                        <div :class="(scope.row.status == 3 && scope.row.cancelStatus == 1)?'blue':(scope.row.status == 3 )?'green':(scope.row.status == 5 )?'reds':''">
                            {{scope.row.status == 1? '核销处理中':scope.row.status == 2? '核销失败':scope.row.status == 3?
                            '核销成功':scope.row.status == 4? '撤销处理中':scope.row.status == 5? '撤销成功':'撤销失败'}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column property="wfUserName" label="操作员" align="center"></el-table-column>
                <el-table-column fixed="right" align="left" label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="wfDetail(scope.row)">详情</el-button>
                        <el-button type="text" v-if="scope.row.status == 3 && scope.row.cancelStatus != 1" size="small"
                                   @click="chengecx(scope.row)">撤销
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                        background
                        @current-change="handleCurrentChange"
                        @size-change="sizechange"
                        :page-size="size"
                        :current-page.sync="page"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                ></el-pagination>
            </div>
        </div>


        <el-dialog
                title="撤销"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">
            <h3>确定撤销此优惠券吗？</h3>
            <span>撤销后将无法修改数据</span>


            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="chengeqrcx">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
    import {
        mdrecord,
        merchantlist,
        shopall,
        writeoffrecordWriteoffCount,
        writeoffCancel,
        exportExcels,
        dictionarylist
    } from "@/api/api";
    import {
        hxrecords,
    } from "@/api/fetchApi";

    export default {
        name: 'item-one',
        data: function () {
            return {
                userInfo: JSON.parse(sessionStorage.getItem('userInfo')),
                dialogVisible: false,
                merchantarr: [],
                page: 1,
                size: 10,
                total: 100,
                exxxx: false,
                loading: false,
                input1: '',
                merchantName: '',
                shopName: '',
                outWfNo: '',
                channelOrderNo: '',
                channelTransId: '',
                channelType: null,
                status: '',
                input6: '',
                input7: '',
                input8: '',
                input9: '',
                options1: [{
                    value: '满减券',
                    label: '满减券'
                }, {
                    value: '折扣券',
                    label: '折扣券'
                }, {
                    value: '随机金额券',
                    label: '随机金额券'
                }],
                options2: [{
                    value: '1',
                    label: '核销中'
                }, {
                    value: '2',
                    label: '核销失败'
                }, {
                    value: '3',
                    label: '核销成功'
                }, {
                    value: '4',
                    label: '撤销处理中'
                }, {
                    value: '5',
                    label: '撤销成功'
                }, {
                    value: '6',
                    label: '撤销失败'
                },],
                channelslist:[],
                options3: [],
                options4: [],
                merchantId: null,
                shopId: null,
                amount: 0,
                count: 0,
                couponAmount: 0,
                ss: {},
                data1Map: new Map(),
                data2Map: new Map(),
                pickerMinDate: null,
                pickerMaxDate: null,
                day31: 31 * 24 * 3600 * 1000,
                pickerOptions1: {
                    // 设置不能超过当天的23:59:59
                    disabledDate(time) {
                        let nowDate = new Date()
                        let date = {
                            year: nowDate.getFullYear(),
                            month: nowDate.getMonth() + 1,
                            date: nowDate.getDate()
                        }
                        let timeDate = date.year + '-' + date.month + '-' + date.date + ' 23:59:59';
                        let times = new Date(timeDate).getTime()
                        return time.getTime() > times
                    }
                },
            };
        },
        created() {
            this.$store.dispatch("getNewNum", 6);
            const start = new Date();
            start.setTime(start.getTime());
            const year = start.getFullYear();
            let month = start.getMonth() + 1;
            if (month < 10) {
                month = '0' + month;
            }
            let date = start.getDate();
            if (date < 10) {
                date = '0' + date;
            }
            const date1 = year + '-' + month + '-' + date + ' 00:00:00';
            const date2 = year + '-' + month + '-' + date + ' 23:59:59';
            this.input7 = [date1, date2];
            this.dictionarylist();
            this.changelist();
            this.chengetotle();
        },
        methods: {
            // 获取所有通道type
            dictionarylist(){
                dictionarylist({type: "couponChannel", status: 0}).then(res => {
                    // console.log(res);
                    if (res.code == 405) {
                        sessionStorage.removeItem("token");
                        this.$router.push("/login");
                    } else {
                        this.channelslist = res.data
                    }
                });
            },
            chengetotle() {
                let ss = {
                    size: this.size,
                    page: this.page,
                    startTime: this.input7 == '' ? '' : this.input7[0],
                    endTime: this.input7 == '' ? '' : this.input7[1]
                }

                writeoffrecordWriteoffCount(ss).then(res => {

                    this.count = res.data.count
                    this.amount = res.data.amount
                    this.couponAmount = res.data.couponAmount
                })
            },
            merchantslist(queryString, cb) {
                let sosolist = {};
                sosolist = {
                    page: 1,
                    size: 20,
                    merchantName: this.merchantName,
                };
                if (this.merchantName != '') {
                    merchantlist(sosolist).then(res => {
                        // console.log(res);
                        if (res.code == 405) {
                            sessionStorage.removeItem("token");
                            this.$router.push("/login");
                        } else {
                            this.merchantarrlist = []
                            for (var i = 0; i < res.data.length; i++) {
                                this.merchantarrlist.push({'value': res.data[i].merchantName, 'id': res.data[i].id})
                            }
                            let results = queryString
                                ? this.merchantarrlist.filter(this.createFilter(queryString))
                                : this.merchantarrlist;
                            // 调用 callback 返回建议列表的数据
                            cb(results);
                        }
                    });
                }
            },
            merid(item) {
                this.merchantId = item.id;
            },
            allshops(queryString, cb) {
                // let allshope = this.allshop;
                let sosolist = {};

                sosolist = {
                    page: 1,
                    size: 20,
                    merchantId: this.merchantId,
                    shopName: this.shopName,
                };

                if (this.userInfo.rolesId == 5) {
                    sosolist = {
                        page: 1,
                        size: 20,
                        merchantId: this.userInfo.mid,
                        shopName: this.shopName
                    };
                } else if (this.userInfo.rolesId != 5 && this.userInfo.rolesId != 6) {
                    sosolist = {
                        page: 1,
                        size: 20,
                        merchantId: this.merchantId,
                        shopName: this.shopName,
                    };
                }

                if (this.shopName != '') {
                    shopall(sosolist).then(res => {
                        // console.log(res);
                        if (res.code == 405) {
                            sessionStorage.removeItem("token");
                            this.$router.push("/login");
                        } else {
                            this.allshop = []
                            for (var i = 0; i < res.data.rows.length; i++) {
                                this.allshop.push({'value': res.data.rows[i].shopName, 'id': res.data.rows[i].id})
                            }
                            let results = queryString
                                ? this.allshop.filter(this.createFilter(queryString))
                                : this.allshop;
                            // 调用 callback 返回建议列表的数据
                            cb(results);
                        }
                    });
                }
            },
            shopid(item) {
                this.shopId = item.id;
            },
            createFilter(queryString) {
                return restaurant => {
                    return (
                        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
                        -1
                    );
                };
            },
            //详情
            wfDetail(item) {
                this.$router.push({
                    path: "/cxparticulars",
                    query: {
                        wfId: item.id
                    }
                });
            },
            //撤销
            chengecx(item) {
                this.dialogVisible = true

                var date = new Date()
                var Y = date.getFullYear() + '-'
                var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
                var D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
                var H = date.getHours() + ':'
                var M2 = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
                var S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

                var aa = Y + M + D + H + M2 + S

                this.ss = {
                    coupon_code: item.couponCode,
                    order_no: item.channelOrderNo,
                    inst_no: '60000001',
                    ts: aa,
                    channel_type: item.channelType,
                    is_all_refund_order: 1,
                    refund_amount: item.writeOffAmount,
                    merchant_id: item.merchantId,
                    shop_id: item.shopId
                }

            },

            //确认撤销
            chengeqrcx() {
                writeoffCancel(this.ss).then(res => {
                    if (res.data.result_code == 'SUCCESS') {
                        this.$message({
                            message: '撤销成功',
                            type: 'success'
                        });
                        this.changelist();
                    } else {
                        this.$message.error(res.data.return_msg);
                    }
                });
                this.dialogVisible = false
            },

            //搜索
            chengess() {
                this.page = 1
                let ss = {
                    page: 1,
                    size: this.size,
                    couponCode: this.input1,
                    merchantId: this.merchantId,
                    shopId: this.shopId,
                    outWfNo: this.outWfNo,
                    channelOrderNo: this.channelOrderNo,
                    channelTransId: this.channelTransId,
                    channelType: this.channelType,
                    status: this.status,
                    wfUserName: this.input6,
                    startTime: this.input7 == null ? '' : this.input7[0],
                    endTime: this.input7 == null ? '' : this.input7[1]
                }

                hxrecords(ss).then(res => {
                    this.merchantarr = res.data.rows
                    this.total = res.data.total
                })

                writeoffrecordWriteoffCount(ss).then(res => {
                    this.count = res.data.count
                    this.amount = res.data.amount
                    this.couponAmount = res.data.couponAmount
                })
            },
            //重置
            chengecz() {
                this.page = 1;
                this.size = 10;
                this.input1 = '';
                this.merchantName = '';
                this.shopName = '';
                this.outWfNo = '';
                this.channelOrderNo = '';
                this.channelTransId= '';
                this.channelType = null;
                this.status = '';
                this.input6 = '';
                this.merchantId = null;
                this.shopId = null;

                const start = new Date();
                start.setTime(start.getTime());
                const year = start.getFullYear();
                let month = start.getMonth() + 1;
                if (month < 10) {
                    month = '0' + month
                }
                let date = start.getDate();
                if (date < 10) {
                    date = '0' + date
                }
                const date1 = year + '-' + month + '-' + date + ' 00:00:00'
                const date2 = year + '-' + month + '-' + date + ' 23:59:59'
                this.input7 = [date1, date2]

                this.changelist()
                this.chengetotle()
            },
            //查询列表
           changelist() {
                let ss = {
                    page: this.page, size: this.size,
                    startTime: this.input7 == null ? '' : this.input7[0],
                    endTime: this.input7 == null ? '' : this.input7[1]
                }

            hxrecords(ss).then(res => {
                    // console.log('请求', res);
                    this.merchantarr = res.data.rows
                    this.total = res.data.total
                })
            },
            handleClose() {
                this.dialogVisible = false
            },
            //多选框
            handleSelectionChange(val) {
                // console.log(val)
                this.multipleSelection = val;
            },
            //修改thead 背景色
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
                }
            },
            // 显示数量
            sizechange(val) {
                // if(this.input1 == '' && this.merchantName == '' && this.shopName == '' && this.channelOrderNo == '' && this.status == '' && this.input6 == '' && this.input7 == null ){
                //       this.size  = val
                //       this.page = 1
                //       this.changelist()
                // }else{
                this.size = val
                this.page = 1

                let ss = {
                    page: 1,
                    size: this.size,
                    couponCode: this.input1,
                    merchantId: this.merchantId,
                    shopId: this.shopId,
                    outWfNo: this.outWfNo,
                    channelOrderNo: this.channelOrderNo,
                    channelTransId: this.channelTransId,
                    channelType: this.channelType,
                    status: this.status,
                    wfUserName: this.input6,
                    startTime: this.input7 == null ? '' : this.input7[0],
                    endTime: this.input7 == null ? '' : this.input7[1]
                }


                hxrecords(ss).then(res => {
                    this.merchantarr = res.data.rows
                    this.total = res.data.total
                })

                // }


            },
            // 分页
            handleCurrentChange(val) {
                this.page = val;
                // console.log('sss', this.input7 == null)


                // if(this.input1 == '' && this.merchantName == '' && this.shopName == '' && this.channelOrderNo == '' && this.status == '' && this.input6 == '' && this.input7 == null ){
                //       console.log('tag', '1111')
                //       this.page = val;
                //       this.changelist()
                // }else{
                this.page = val


                let ss = {
                    page: this.page,
                    size: this.size,
                    couponCode: this.input1,
                    merchantId: this.merchantId,
                    shopId: this.shopId,
                    outWfNo: this.outWfNo,
                    channelOrderNo: this.channelOrderNo,
                    channelTransId: this.channelTransId,
                    channelType: this.channelType,
                    status: this.status,
                    wfUserName: this.input6,
                    startTime: this.input7 == null ? '' : this.input7[0],
                    endTime: this.input7 == null ? '' : this.input7[1]

                }


                hxrecords(ss).then(res => {
                    this.merchantarr = res.data.rows
                    this.total = res.data.total
                })

                // }

            },
            // 导出
            merchantexcel() {
                if (this.input7 == '') {
                    //  loading.close();
                    return this.$message.error('请选择日期后在导出');
                } else {
                    const loading = this.$loading({
                        lock: true,
                        text: '导出操作可能耗时较长，请耐心等待',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });

                    var sosolist = {}
                    sosolist = {
                        page: this.page,
                        size: this.size,
                        couponCode: this.input1,
                        merchantId: this.merchantId,
                        shopId: this.shopId,
                        outWfNo: this.outWfNo,
                        channelOrderNo: this.channelOrderNo,
                        channelTransId: this.channelTransId,
                        channelType: this.channelType,
                        status: this.status,
                        wfUserName: this.input6,
                        startTime: this.input7[0],
                        finishTime: this.input7[1],
                        exportType: 2
                    }

                    exportExcels(sosolist).then(res => {
                        if (res.data.code == 405) {
                            sessionStorage.removeItem('token')
                            this.$router.push('/login');
                            loading.close();
                        } else if (res.data.code == 200) {
                            this.$message({
                                message: '导出申请成功，请到导出任务列表中下载',
                                type: 'success'
                            });
                            loading.close();
                        } else {
                            this.$message.error(res.data.message);
                            loading.close();
                        }
                    })
                }
            },
            renderheader(h, {column, $index}) {
                return h("span", {}, [
                    h("span", {}, column.label.split("?")[0]),
                    h("br"),
                    h("span", {}, column.label.split("?")[1])
                ]);
            },
            // 跳转导出
            joinexportlist() {
                this.$router.push('/hxexportlist');
            }
        }
    };
</script>
<style scoped>
    .red {
        color: red;
    }

    .chengeinout {
        width: 190px;
        margin-right: 20px;
        margin-bottom: 10px;
    }

    .date-picker {
        margin-right: 10px;
        margin-bottom: 10px;
    }

    .chengebutton {
        margin-left: 10px;
        padding: 0 30px;
        height: 32px;
    }

    .title {
        background: #fff;
        padding: 10px 10px;
        font-size: 18px;
        font-weight: 500;
        display: flex;
        justify-content: space-between;
    }

    .name {
        width: 25%;
    }

    .screeningBox {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
    }

    .leftBox,
    .rightBox {
        width: 50%;
        padding: 0 15px;
        box-sizing: border-box;
    }

    .leftBox > .leftitem {
        margin-bottom: 15px;
    }

    .rightBox > .rightitem {
        margin-bottom: 15px;
    }

    .merchants {
        width: 50%;
    }

    .tableBox {
        margin-top: 20px;
    }

    .servicename {
        width: 60%;
    }

    .servicelevel {
        width: 20%;
    }

    .width20 {
        width: 20%;
    }

    .width30 {
        width: 30%;
    }

    .red {
        color: #f9607d;
    }

    .stitle {
        padding: 5px 0;
        font-size: 18px;
    }

    .statistical {
        width: 100%;
        display: flex;
        justify-content: space-around;
        align-items: center;
        background: #00152a;
        color: #fff;
        padding: 12px;
        box-sizing: border-box;
    }

    .statistical > .statisticalitem {
        text-align: center;
        line-height: 200%;
    }

    .BDname {
        width: 20%;
    }

    .width60 {
        width: 40%;
    }

    .yuan {
        color: #C1C5CB;
        font-size: 12px;
        position: relative;
        left: -20px;
    }

    .green {
        width: 70px;
        background: #97C05C;
        color: #fff;
        padding: 0 5px;
        border-radius: 10px;
    }

    .orange {
        width: 70px;
        background: #F29C38;
        color: #fff;
        padding: 0 5px;
        border-radius: 10px;
    }

    .hui {
        width: 70px;
        background: #888888;
        color: #fff;
        padding: 0 5px;
        border-radius: 10px;
    }

    .reds {
        width: 70px;
        background: #D3362F;
        color: #fff;
        padding: 0 5px;
        border-radius: 10px;
    }

    .blue {
        width: 70px;
        background: #4154AF !important;
        color: #fff;
        padding: 0 5px;
        border-radius: 10px;
    }

</style>
